<template>
 <z-paging ref="paging"
           v-model="orderList"
           @query="queryList"
           height="100vh"
           :paging-style="{minHeight: '100vh', backgroundColor: '#F0F4F3'}">
   <template #top>
     <view class="navbar">
       <view v-for="(item, index) in navList" :key="index" class="nav-item"
             :class="{current: tabCurrentIndex === index}" @click="tabClick(index)">
         <text>{{item.text}}</text>
       </view>
     </view>
   </template>

   <!-- 订单内容区域 - 横向排列实现翻页效果 -->
   <view class="content-box">
     <!-- 横向排列所有tab内容 -->
     <view class="tabs-container" :style="{transform: `translateX(-${tabCurrentIndex * 100}%)`}">
       <view v-for="(tabItem,tabIndex) in navList"
             :key="tabIndex"
             class="tab-content">
         <view class="list-scroll-content" :class="{'animate-in': tabCurrentIndex === tabIndex}">
           <!-- 订单列表 -->
		   <view v-for="(item,index) in orderList" :key="index">
           <view class="order-item" :style="{'--item-index': index}">
             <!-- 订单编号与状态 -->
             <view class="order-number">
               <text class="number">{{$t('orders.orderNumber')}}：{{item.OrdersOnLineId}}  <text v-if="item.OrdersOnLineType == 5" class="package">(套餐产品)</text></text>
			   
               <text class="status">{{statusTitle(item.Type, item.ProductType)}}</text>
             </view>

             <!-- 订单商品信息 -->
             <view v-for="(goodsItem, goodsIndex) in item.OrdersOnlineInfoViewList" :key="goodsIndex"
                   @click="navToDetail(item,'order/details',goodsIndex)"
                   class="goods-item">
               <view class="item-content">
                 <image class="goods-img" :src="goodsItem.Img" mode="aspectFill"></image>
                 <view class="goods-info">
				   <view class="goods-t">
						<view class="goods-t-l">
							<view class="goods-name">
								<text>{{goodsItem.ProductName}}</text>
							</view>
						</view>
						<view class="goods-t-r">
							<!-- <view v-if="item.OrdersOnLineType == 5" class="price linePrice">{{ getActualPayment(goodsItem) }}</view> -->
							<view v-if="item.OrdersOnLineType != 5" class="price">{{ getActualPayment(goodsItem) }}</view>
                     		<view class="quantity">×{{goodsItem.Num}}</view>
						</view>
				   </view>
				   <view class="goods-b">
						<view class="goods-b-l">
							<view>
								<view class="goods-date">{{item.AddTime}}</view>
								<view class="goods-seller">{{item.BusinessModel ? item.BusinessModel.ShopName : ''}}</view>
							</view>
						</view>
						<view class="goods-b-r" v-if="item.OrdersOnLineType !== 5">
							<view class="order-total" >{{$t('orders.actualPayment')}}<text class="total-price">{{ getActualPayment(goodsItem) }}</text></view>
						</view>
				   </view>
                 </view>
               </view>
             </view>
             <view class="order-x"></view>

             <!-- 订单操作按钮 -->
             <view class="order-actions">
               <!-- 未付款操作 -->
               <view v-if="item.Type === 17" class="btns">
                 <button class="action-btn cancel" @click.stop="showPopup(1,item,item.OrdersOnlineInfoViewList)">{{$t('orders.actions.cancel')}}</button>
                 <button class="action-btn pay" @click.stop="jumpPayment(item)">{{$t('orders.actions.pay')}}</button>
               </view>

               <!-- 待收货操作 -->
               <view v-if="[1].includes(item.Type)" class="btns">
                 <button class="action-btn cancel" @click.stop="navToDetail(item,'order/details')">{{$t('orders.actions.viewDetails')}}</button>
                 <button class="action-btn pay" @click.stop="receipt(item)">{{$t('orders.actions.confirmReceipt')}}</button>
               </view>

               <!-- 待评价操作 -->
               <view v-if="[2,6].includes(item.Type)" class="btns">
                 <button class="action-btn cancel" @click.stop="navToDetail(item,'order/details')">{{$t('orders.actions.viewDetails')}}</button>
                 <button class="action-btn pay" @click.stop="navToDetail(item,'evaluation/evaluation',0)">{{$t('orders.actions.evaluate')}}</button>
               </view>

               <!-- 申请退款操作 -->
               <view v-if="[15, 18, 2].includes(item.Type)" class="btns">
                 <button class="action-btn cancel" @click.stop="navToDetail(item,'order/details')">{{$t('orders.actions.viewDetails')}}</button>
                 <button class="action-btn cancel" @click.stop="showPopup(2,item,item.OrdersOnlineInfoViewList)">{{$t('orders.actions.refund')}}</button>
               </view>

               <!-- 默认仅查看详情 -->
               <view v-if="![1, 2, 6, 15, 17, 18].includes(item.Type)" class="btns">
                 <button class="action-btn cancel" @click.stop="navToDetail(item,'order/details')">{{$t('orders.actions.viewDetails')}}</button>
               </view>
             </view>
           </view>
		</view>
         </view>
       </view>
     </view>
   </view>

   <template #bottom>
     <cancel-popup ref="refcancel" @ok="handleOk"></cancel-popup>
     <TabBar :isFixed="false"></TabBar>
     <hz-safe-area></hz-safe-area>
   </template>
 </z-paging>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
  import {
    getUserOrderList,
    cancelOrders,
    refundOrders,
    productOrdersPay,
    acceptOrders, 
    refundShipTickets,
    QueryRefundFee,
    getOrderDetails
  } from '@/api/mall.js'
	import empty from "@/components/empty";
	import cancelPopup from '@/components/cancel-popup.vue'
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		orderStateExp
	} from '@/utils/base.js'
	import TabBar from "@/components/layout/tabbar/index.vue";
  import HzSafeArea from "@/components/layout/hz/hz-safe-area.vue";
  import HzTag from "@/components/layout/hz/hz-tag.vue";

	export default {
		components: {
      HzSafeArea,
			TabBar,
			uniLoadMore,
			empty,
      HzTag,
			cancelPopup,
		},
		data() {
			return {
        paging: null,
				tabCurrentIndex: 0,
				showLogisticsStatus: [2, 3, 6], // 显示物流信息状态
        orderList: [],
				navList: [],
				navType: 1,
				isProcessing: false, // 控制请求状态
			};
		},
		computed: {
			...mapState({
				userInfo: state => state.base.userInfo,
        order: state => state.tabBar.order
			}),
		},
    watch: {
      order(newVal, oldVal) {
        this.tabCurrentIndex = newVal
      },
      '$i18n.locale'() {
        this.updateNavigationBarTitle();
        this.initNavList();
      }
    },
		onUnload() {
			console.log('load')
		},
		filters: {
			goodsImage(e) {
				let arr = JSON.parse(e) || []
				return arr[0]
			},
			toFixd(e) {
				let price = e * 1 || 0
				return price > 0 ? price.toFixed(2) : 0
			}
		},
		created() {
      this.initNavList();
		},
		onLoad(options) {
      this.updateNavigationBarTitle();
		},
		methods: {
			...mapMutations(['setOrderDetail']),

      // 更新导航栏标题
      updateNavigationBarTitle() {
        uni.setNavigationBarTitle({
          title: this.$t('orders.title')
        });
      },

      // 初始化导航列表
      initNavList() {
        this.navList = [{
          state: 0,
          text: this.$t('orders.tabs[0]'),
          loadingType: 'more',
          orderList: [],
          parma: {
            TypeArr: ""
          },
          page: 1,
          pageSize: 10
        },
        {
          state: 1,
          text: this.$t('orders.tabs[1]'),
          loadingType: 'more',
          orderList: [],
          parma: {
            TypeArr: "17"
          },
          page: 1,
          pageSize: 10
        },
        {
          state: 2,
          text: this.$t('orders.tabs[2]'),
          loadingType: 'more',
          orderList: [],
          parma: {
            TypeArr: '15,20',
            IsOnline: 1
          },
          page: 1,
          pageSize: 10,
        },
        {
          state: 3,
          text: this.$t('orders.tabs[3]'),
          loadingType: 'more',
          orderList: [],
          parma: {
            TypeArr: '1,15,20',
            IsOnline: 0
          },
          page: 1,
          pageSize: 10
        },
        // {
        //   state: 4,
        //   text: this.$t('orders.tabs[4]'),
        //   loadingType: 'more',
        //   orderList: [],
        //   parma: {
        //     TypeArr: '3,4,7,8,9,10,11,12'
        //   },
        //   page: 1,
        //   pageSize: 10
        // },
		{
		  state: 5,
          text: this.$t('orders.tabs[5]'),
          loadingType: 'more',
          orderList: [],
          parma: {
            TypeArr: '2,4,5,6'
          },
          page: 1,
          pageSize: 10
		}];
      },

      statusTitle(t, s) {
        return orderStateExp(t, s).stateTip
      },
      queryList(pageNo, pageSize) {
        let navItem = this.navList[this.tabCurrentIndex];
		console.log("navItem =>",navItem);
        // 显示加载中状态
        if(pageNo === 1) {
          uni.showLoading({
            title: this.$t('orders.orderList.loading'),
            mask: false
          });
        }

        getUserOrderList({
          Index: pageNo,
          Size: pageSize,
          ...navItem.parma
        }).then(res => {
          const data = res.Data || [];
          this.$refs.paging.complete(data);

          // 清除加载状态
          if(pageNo === 1) {
            uni.hideLoading();
          }

          // 移除手动处理数据的代码，因为z-paging会自动管理orderList数据
        }).catch(err => {
          if(pageNo === 1) {
            uni.hideLoading();
          }
          this.$refs.paging.complete(false);
        });
      },
			//获取订单列表
			async loadData(type = 'add') {
				//这里是将订单挂载到tab列表下
				let index = this.tabCurrentIndex;
				let navItem = this.navList[index];
				let parma = navItem.parma;
				if (type === 'tabChange' && navItem.loaded === true) {
					return;
				}

				if (type === 'refresh') {
					navItem.page = 1
				}

				if (type === 'add' || type === 'tabChange') {
					if (navItem.loadingType === 'nomore') {
						return;
					}
					navItem.loadingType = 'loading';
				} else {
					navItem.loadingType = 'more'
				}

				let {
					Data,
					Total
				} = await getUserOrderList({
					Index: navItem.page,
					Size: navItem.pageSize,
					...navItem.parma
				})
				console.log(3333, Data)
				if (type === 'tabChange' && !navItem.loaded) {
					this.$set(navItem, 'loaded', true)
				}

				let list = Data
				if (type === 'refresh') {
					navItem.orderList = [];
				}
				navItem.orderList = navItem.orderList.concat(list)
				//判断是否还有下一页，有是more并且页数加1  没有是nomore
				if (navItem.orderList.length < Total) {
					navItem.loadingType = 'more'
					navItem.page++
				} else {
					navItem.loadingType = 'nomore'
				}
			},
			//tab 切换
			tabClick(index) {
				if(this.tabCurrentIndex === index) return;

				// 切换前清空当前列表
				this.orderList = [];
				this.tabCurrentIndex = index;

				// 延迟一点时间再加载数据，让DOM有时间更新
				setTimeout(() => {
				  this.$refs.paging.reload();
				}, 100);
			},
			// 跳转商品详情
			navGoodsDetail(item) {
				console.log("item", item)
				const {
					Type,
					OrdersOnlineInfoViewList
				} = item;
				let Id = OrdersOnlineInfoViewList?.[0]?.ProductId
				let url = `/mall_subpages/goods-detail/goods-detail?id=${Id}&type=${Type}`
				uni.navigateTo({
					url
				})
			},
			//跳转详情页
			navToDetail(item, page, index) {
				console.log('跳转详情页', item, page, index)
				let detail = this.$api.deepClone(item)
				console.log(detail)
				if (index !== undefined) {
					detail.OrdersOnlineInfoViewList = detail.OrdersOnlineInfoViewList.filter((t, i) => i === index)
				}
				this.setOrderDetail(detail)
				let url = `/mall_subpages/${page}?id=${detail.Id}&index=${index}`
				console.log("OrdersOnLineType =>",item.OrdersOnLineType);
				if(item.OrdersOnLineType == 5){
					url+= '&isPackage=true'
				}
				uni.navigateTo({
					url
				})
			},
      jumpPayment(item){
        uni.navigateTo({
          url: `/mall_subpages/goods/payment?id=${item.OrdersOnLineId}&delta=1`
        })
      },
			//支付未支付订单
			async payOrder(item, index) {
				const _this = this
				try {
					uni.showLoading({
						title: '提交中...',
						mask: true
					})

					const {
						Data
					} = await productOrdersPay({
						"OrdersOnLineId": item.OrdersOnLineId,
						"OrdersOnLineType": item.OrdersOnLineType,
						"Remark": ""
					})
					const params = JSON.parse(Data.WxJsApiParam)
					console.log('!!!', params)
					// uni.hideLoading()
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: params.timeStamp,
						nonceStr: params.nonceStr,
						package: params.package,
						signType: params.signType,
						paySign: params.paySign,
						success: function(res) {
							uni.hideLoading()
							// _this.loadData('refresh')
              _this.$refs.paging.refresh()
							_this.clearData(_this.tabCurrentIndex)
						},
						fail: function(err) {
							uni.hideLoading()
							console.log('fail:' + JSON.stringify(err));
						}
					});
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: e.Msg,
						icon: 'none',
						duration: 2000
					})
					console.error('支付失败:', e)
				}
			},
			//确认收货
			async receipt(item) {
				let _this = this
				const params = item.OrdersOnlineInfoViewList.map(row => {
					return {
						"InfoId": row.Id,
						"Remark": "",
						"ProductOrdersCouponInfoCode": row.Code,
						"LogisticsName": "",
						"LogisticsANO": "",
						"OrdersOnLineId": row.OrdersOnLineId,
						"OrdersOnLineType": row.OrdersOnLineType
					}
				})

				try {
					uni.showLoading({
						title: this.$t('orders.orderList.pleaseWait')
					})
					const {
						Data
					} = await acceptOrders(params)
					this.$api.msg(this.$t('orders.orderList.receiptSuccess'))
					this.$refs.paging.refresh()
					this.clearData(this.tabCurrentIndex)
					uni.hideLoading()
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: e.Msg,
						icon: 'none',
						duration: 2000
					})
					console.error(this.$t('orders.orderList.receiptFailed'), e)
				}
			},
			//显示选择理由popup
			showPopup(type, item, goodsItem) {
        if(item.BusinessModel.Id === 35){
          // 船票订单，处理退票逻辑
          if(type === 2) { // 申请退款
            this.handleShipTicketRefund(item, goodsItem);
          } else {
            // 取消订单，使用普通弹窗
            this.$refs.refcancel.show({
              type,
              item,
              goodsItem
            });
          }
        } else {
          this.$refs.refcancel.show({
            type,
            item,
            goodsItem
          })
        }
			},
			handleOk(e) {
				if (e.type === 1) {
					this.handleCancelOrder(e)
				} else if (e.type === 2) {
					this.handleRefundOrder(e)
				}
			},
			//申请退款
			async handleRefundOrder({
				item,
				goodsItem,
				title,
				LogisticsName,
				LogisticsANO
			}) {
				let _this = this
				uni.showLoading({
					title: this.$t('orders.orderList.pleaseWait'),
					mask: true
				})
				try {
					const params = goodsItem.map(row => {
						return {
							"InfoId": row.Id,
							"Remark": title,
							"LogisticsName": LogisticsName,
							"LogisticsANO": LogisticsANO,
							"ProductOrdersCouponInfoCode": row.Code,
							"OrdersOnLineId": item.OrdersOnLineId,
							"OrdersOnLineType": item.OrdersOnLineType,
						}
					})
					await refundOrders(params)
					uni.hideLoading()
					_this.$refs.refcancel.hide()
					_this.$api.msg(this.$t('orders.orderList.applicationSuccess'))
					_this.$refs.paging.refresh()
					_this.clearData(_this.tabCurrentIndex)
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: e.Msg,
						icon: 'none',
						duration: 2000
					})
					console.error(this.$t('orders.orderList.refundFailed'), e)
				}
			},
			//取消订单
			async handleCancelOrder({
				item,
				title
			}) {
				let _this = this
				console.log(444444, item, item.OrdersOnLineId, item.OrdersOnLineType, title);
				uni.showLoading({
					title: this.$t('orders.orderList.pleaseWait'),
					mask: true
				})
				try {
					const {
						Data
					} = await cancelOrders({
						"OrdersOnLineId": item.OrdersOnLineId,
						"OrdersOnLineType": item.OrdersOnLineType,
						"Remark": title
					});
					console.log(44444444444555, Data)
					this.$api.msg(this.$t('orders.orderList.cancelSuccess'))
					this.$refs.refcancel.hide()
					this.$refs.paging.refresh()
					this.clearData(this.tabCurrentIndex)
					uni.hideLoading()
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: e.Msg,
						icon: 'none',
						duration: 2000
					})
					console.error(this.$t('orders.orderList.cancelFailed'), e)
				}
			},
			clearData(tIndex) {
				this.navList.forEach((item, index) => {
					if (tIndex !== index) {
						item.loadingType = 'more'
						item.page = 1
						item.loaded = false
						item.orderList = []
					}
				})
			},
			back() {
				uni.switchTab({
					url: '/pages/userCenter/center'
				})
			},
			// 处理船票订单退票
			async handleShipTicketRefund(item, goodsItem) {
				console.log(goodsItem);
				
				try {
					uni.showLoading({
						title: '获取订单详情...'
					});

					// 先获取订单详情以获取船票信息
					const orderDetailResponse = await getOrderDetails({
						OrdersOnLineId: item.OrdersOnLineId
					});

					if (!orderDetailResponse.Data) {
						uni.hideLoading();
						uni.showToast({
							title: '获取订单详情失败',
							icon: 'none'
						});
						return;
					}

					const orderDetail = orderDetailResponse.Data;
					const productList = orderDetail.ProductOrdersInfoList || [];

					if (productList.length === 0) {
						uni.hideLoading();
						uni.showToast({
							title: '未找到船票信息',
							icon: 'none'
						});
						return;
					}

					// 更新加载提示
					uni.showLoading({
						title: '查询退票信息...'
					});

					// 判断是单程票还是往返票
					if (productList.length === 1) {
						// 单程票处理
						await this.handleSingleTripRefund(item, orderDetail, productList[0]);
					} else if (productList.length === 2) {
						// 往返票处理
						await this.handleRoundTripRefund(item, orderDetail, productList);
					} else {
						uni.hideLoading();
						uni.showToast({
							title: '订单数据异常',
							icon: 'none'
						});
					}

				} catch (error) {
					uni.hideLoading();
					console.error('查询船票退票费用失败:', error);
					uni.showToast({
						title: '查询退票信息失败，请稍后重试',
						icon: 'none'
					});
				}
			},

			// 处理单程票退票
			async handleSingleTripRefund(item, orderDetail, productInfo) {
				try {
					const shipOrderNo = productInfo.ShipOrderNo;
					if (!shipOrderNo) {
						uni.hideLoading();
						uni.showToast({
							title: '未找到船票订单号',
							icon: 'none'
						});
						return;
					}

					// 查询退票费用
					const response = await QueryRefundFee({
						orderNo: shipOrderNo
					});

					uni.hideLoading();

					if (response.Code === '200' && response.Data) {
						const refundData = response.Data;
						this.showRefundConfirmDialog(item, orderDetail, [refundData], '单程票');
					} else {
						uni.showToast({
							title: response.Msg || '查询退票信息失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					throw error;
				}
			},

			// 处理往返票退票
			async handleRoundTripRefund(item, orderDetail, productList) {
				try {
					const refundPromises = [];
					const shipOrderNos = [];

					// 分别查询去程和返程的退票费用
					for (let i = 0; i < productList.length; i++) {
						const productInfo = productList[i];
						const shipOrderNo = productInfo.ShipOrderNo;
						
						if (!shipOrderNo) {
							uni.hideLoading();
							uni.showToast({
								title: `未找到第${i + 1}程船票订单号`,
								icon: 'none'
							});
							return;
						}

						shipOrderNos.push(shipOrderNo);
						refundPromises.push(QueryRefundFee({ orderNo: shipOrderNo }));
					}

					// 并发查询所有退票费用
					const responses = await Promise.all(refundPromises);
					
					uni.hideLoading();

					// 检查所有响应是否成功
					const refundDataList = [];
					for (let i = 0; i < responses.length; i++) {
						const response = responses[i];
						if (response.Code === '200' && response.Data) {
							refundDataList.push(response.Data);
						} else {
							uni.showToast({
								title: `查询第${i + 1}程退票信息失败：${response.Msg || '未知错误'}`,
								icon: 'none'
							});
							return;
						}
					}

					this.showRefundConfirmDialog(item, orderDetail, refundDataList, '往返票');

				} catch (error) {
					uni.hideLoading();
					throw error;
				}
			},

			// 显示退票确认对话框
			showRefundConfirmDialog(item, orderDetail, refundDataList, tripType) {
				// 计算总退票信息
				let totalTicketPrice = 0;
				let totalRefundAmount = 0;
				let totalRefundRateAmount = 0;
				let totalTicketCount = 0;

				let tripDetails = [];

				refundDataList.forEach((refundData, index) => {
					if (refundData.detailList && refundData.detailList.length > 0) {
						let tripTicketPrice = 0;
						let tripRefundAmount = 0;
						let tripRefundRateAmount = 0;
						let tripTicketCount = refundData.detailList.length;

						refundData.detailList.forEach(ticket => {
							tripTicketPrice += parseFloat(ticket.ticketPrice) || 0;
							tripRefundAmount += parseFloat(ticket.refundAmount) || 0;
							tripRefundRateAmount += parseFloat(ticket.refundRateAmount) || 0;
						});

						tripDetails.push({
							name: tripType === '往返票' ? (index === 0 ? '去程' : '返程') : '单程',
							ticketCount: tripTicketCount,
							ticketPrice: tripTicketPrice,
							refundAmount: tripRefundAmount,
							refundRateAmount: tripRefundRateAmount
						});

						totalTicketPrice += tripTicketPrice;
						totalRefundAmount += tripRefundAmount;
						totalRefundRateAmount += tripRefundRateAmount;
						totalTicketCount += tripTicketCount;
					}
				});

				// 构建确认消息
				let content = `${tripType}退票确认\n\n`;
				
				tripDetails.forEach(trip => {
					content += `${trip.name}：${trip.ticketCount}张票\n`;
					content += `票价：¥${trip.ticketPrice.toFixed(2)}\n`;
					content += `手续费：¥${trip.refundRateAmount.toFixed(2)}\n`;
					content += `退款：¥${trip.refundAmount.toFixed(2)}\n\n`;
				});

				content += `总计：\n`;
				content += `总票数：${totalTicketCount}张\n`;
				content += `总票价：¥${totalTicketPrice.toFixed(2)}\n`;
				content += `总手续费：¥${totalRefundRateAmount.toFixed(2)}\n`;
				content += `总退款金额：¥${totalRefundAmount.toFixed(2)}\n`;
				
				if (refundDataList[0].detailList && refundDataList[0].detailList[0].remarks) {
					content += `说明：${refundDataList[0].detailList[0].remarks}\n`;
				}
				
				content += `\n确定要退票吗？`;

				uni.showModal({
					title: '船票退票确认',
					content: content,
					success: (res) => {
						if (res.confirm) {
							this.refundAllShipTickets(item, orderDetail, refundDataList);
						}
					}
				});
			},

			// 从订单详情中获取船票订单号
			getShipOrderNoFromDetail(orderDetail) {
				if (!orderDetail || !orderDetail.ProductOrdersInfoList) {
					return null;
				}
				// 遍历ProductOrdersInfoList查找船票信息
				for (let productInfo of orderDetail.ProductOrdersInfoList) {
					if (productInfo.ShipOrderNo) {
						return productInfo.ShipOrderNo;
					}
					if (productInfo.ShipTicketList && Array.isArray(productInfo.ShipTicketList) && productInfo.ShipTicketList.length > 0) {
						return productInfo.ShipTicketList[0].OrderNo;
					}
				}
				return null;
			},

			// 获取船票订单号 
			getShipOrderNo(goodsItem) {
				for (let item of goodsItem) {
					if (item.ShipOrderNo) {
						return item.ShipOrderNo;
					}
					if (item.ShipTicketList && Array.isArray(item.ShipTicketList) && item.ShipTicketList.length > 0) {
						return item.ShipTicketList[0].OrderNo;
					}
				}
				return null;
			},

			// 退所有船票
			async refundAllShipTickets(item, orderDetail, refundDataList) {
				try {
					uni.showLoading({
						title: '退票中...'
					});

					const productList = orderDetail.ProductOrdersInfoList || [];
					const orderNos = [];

					// 收集所有需要退票的订单号
					for (let i = 0; i < productList.length; i++) {
						const productInfo = productList[i];
						
						if (productInfo.ShipTicketList && Array.isArray(productInfo.ShipTicketList) && productInfo.ShipTicketList.length > 0) {
							const orderNo = productInfo.ShipTicketList[0].OrderNo;
							
							if (orderNo) {
								orderNos.push(orderNo);
							}
						}
					}

					if (orderNos.length === 0) {
						uni.hideLoading();
						uni.showToast({
							title: '未找到可退票的订单',
							icon: 'none'
						});
						return;
					}

					// 顺序执行退票操作，避免频率限制
					const responses = [];
					for (let i = 0; i < orderNos.length; i++) {
						// 更新进度提示
						if (orderNos.length > 1) {
							uni.showLoading({
								title: `退票中... (${i + 1}/${orderNos.length})`
							});
						}
						
						if (i > 0) {
							// 在第二次及后续调用前等待1秒
							await new Promise(resolve => setTimeout(resolve, 1000));
						}
						
						try {
							const response = await refundShipTickets({
								OrderNo: orderNos[i]
							});
							responses.push(response);
						} catch (error) {
							// 如果单个请求失败，也要记录失败响应
							responses.push({
								Code: 'ERROR',
								Msg: error.message || '网络错误'
							});
						}
					}
					
					uni.hideLoading();

					// 检查退票结果
					let successCount = 0;
					let failCount = 0;
					let totalTicketCount = 0;
					
					// 计算总票数
					refundDataList.forEach(refundData => {
						if (refundData.detailList) {
							totalTicketCount += refundData.detailList.length;
						}
					});

					// 检查每个退票响应
					responses.forEach((response, index) => {
						if (response.Code === '200') {
							successCount++;
						} else {
							failCount++;
							console.error(`退票失败 OrderNo: ${orderNos[index]}, 原因: ${response.Msg}`);
						}
					});

					// 显示退票结果
					if (successCount > 0) {
						let message;
						if (failCount > 0) {
							message = `退票完成：成功${successCount}程，失败${failCount}程`;
						} else {
							message = productList.length === 1 
								? `成功退票 ${totalTicketCount} 张`
								: `成功退票往返 ${totalTicketCount} 张`;
						}
						
						uni.showToast({
							title: message,
							icon: successCount === responses.length ? 'success' : 'none',
							duration: 2000
						});

						// 刷新订单列表
						setTimeout(() => {
							this.$refs.paging.refresh();
							this.clearData(this.tabCurrentIndex);
						}, 1500);
					} else {
						uni.showToast({
							title: '退票失败，请稍后重试',
							icon: 'none'
						});
					}

				} catch (error) {
					uni.hideLoading();
					console.error('退票失败:', error);
					uni.showToast({
						title: '退票失败，请稍后重试',
						icon: 'none'
					});
				}
			},

			getActualPayment(item) {
				const point = this.$t('orders.actualPaymentPoint');
				const unit = this.$t('orders.actualPaymentUnit');
				if (item.SalePointTotal) return `${item.SalePointTotal} ${point}`;
				const toFixd = this.$options.filters.toFixd;
				return `${unit} ${toFixd(item.SalePrice)}`;
			}
		},
	}
</script>

<style lang="scss">
	/* 顶部导航栏样式 */
	.navbar {
		display: flex;
		height: 98rpx;
		background: #FFFFFF;
		position: relative;
		z-index: 10;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.nav-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 24rpx;
			color: #666;
			position: relative;
			transition: all 0.3s ease;
			cursor: pointer;

			text{
				display: inline-block;
				padding: 10rpx 30rpx;
				border-radius: 30rpx;
				transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
				position: relative;
				z-index: 1;

				&:after {
					content: '';
					position: absolute;
					bottom: 6rpx;
					left: 50%;
					width: 0;
					height: 3rpx;
					background-color: #00BFFF;
					transition: width 0.3s ease, left 0.3s ease;
					z-index: 0;
				}
			}

			&:active text {
				transform: scale(0.95);
			}

			&.current {
				text{
					font-size: 30rpx;
					font-weight: 600;
					background-color: #00BFFF;
					color: #FFFFFF;
					transform: translateY(0) scale(1);
					animation: popIn 0.4s ease;

					@keyframes popIn {
						0% {
							transform: translateY(10rpx) scale(0.9);
							opacity: 0.7;
						}
						70% {
							transform: translateY(-5rpx) scale(1.05);
						}
						100% {
							transform: translateY(0) scale(1);
						}
					}
				}

				&:after {
					content: none;
				}
			}
		}
	}

	/* 内容区域样式 */
	.content-box {
		position: relative;
		width: 100%;
		overflow: hidden;
	}

	/* 横向排列的tab容器 */
	.tabs-container {
		display: flex;
		width: 100%;
		transition: transform 0.4s cubic-bezier(0.23, 1, 0.32, 1);
		will-change: transform;
	}

	.tab-content {
		flex: 0 0 100%;
		width: 100%;
	}

	.list-scroll-content {
		height: 100%;
		padding: 20rpx;
    box-sizing: border-box;
	}

	/* 订单项样式 */
	.order-item {
		background: #FFFFFF;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
		padding: 0;
		transform: translateY(20rpx);
		opacity: 0;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
		animation: none;
		will-change: transform, opacity;

		/* 使用CSS动画延迟依次显示 */
		&:nth-child(1) { animation: fadeInUp 0.4s ease forwards 0.05s; }
		&:nth-child(2) { animation: fadeInUp 0.4s ease forwards 0.1s; }
		&:nth-child(3) { animation: fadeInUp 0.4s ease forwards 0.15s; }
		&:nth-child(4) { animation: fadeInUp 0.4s ease forwards 0.2s; }
		&:nth-child(5) { animation: fadeInUp 0.4s ease forwards 0.25s; }
		&:nth-child(6) { animation: fadeInUp 0.4s ease forwards 0.3s; }
		&:nth-child(7) { animation: fadeInUp 0.4s ease forwards 0.35s; }
		&:nth-child(8) { animation: fadeInUp 0.4s ease forwards 0.4s; }
		&:nth-child(9) { animation: fadeInUp 0.4s ease forwards 0.45s; }
		&:nth-child(10) { animation: fadeInUp 0.4s ease forwards 0.5s; }
		&:nth-child(n+11) { animation: fadeInUp 0.4s ease forwards 0.55s; }

		/* 入场动画 */
		@keyframes fadeInUp {
			from {
				opacity: 0;
				transform: translateY(20rpx);
			}
			to {
				opacity: 1;
				transform: translateY(0);
			}
		}

		/* 悬停效果 */
		&:active {
			transform: scale(0.98);
			box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.08);
		}

		/* 订单编号与状态 */
		.order-number {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 24rpx;
			border-bottom: 0;

			.number {
				font-size: 28rpx;
				color: #666;
				.package{
					padding-left: 20rpx;
					color: #0094de;
					font-weight: 600;
				}
			}

			.status {
				font-size: 28rpx;
				color: #FA452D;
				position: relative;
				overflow: hidden;

				&:after {
					content: '';
					position: absolute;
					bottom: -2rpx;
					left: 0;
					width: 0;
					height: 2rpx;
					background-color: #FA452D;
					transition: width 0.3s ease;
				}

				&:active:after {
					width: 100%;
				}
			}
		}

    .order-x{
      border-top: 1rpx solid #EDEDED;
    }

		/* 商品项样式 */
		.goods-item {
			padding: 16rpx 24rpx;
			border-bottom: 0;
			transition: background-color 0.2s ease;
			&:active {
				background-color: rgba(0, 0, 0, 0.02);
			}
			.item-content {
				display: flex;
			}
			.goods-img {
				width: 140rpx;
				height: 140rpx;
				border-radius: 12rpx;
				transition: transform 0.3s ease;
				&:active {
					transform: scale(1.05);
				}
			}
			.goods-info {
				flex: 1;
				min-height: 140rpx;
				max-height: 160rpx;
				padding-left: 20rpx;
				display: flex;
				flex-direction: column;
				.goods-t {
					display: flex;
					height: 80rpx;
					&-l {
						flex: 1;
						.goods-name {
							font-size: 28rpx;
							color: #333;
							font-weight: 600;
							display: -webkit-box;
							-webkit-line-clamp: 2;
							overflow: hidden;
							-webkit-box-orient: vertical;
						}
					}
					&-r {
						display: flex;
						flex-direction: column;
						flex-shrink: 0;
						align-items: flex-end;
						margin-left: 24rpx;
						.price {
							font-size: 24rpx;
							&.linePrice{
								  text-decoration: line-through;
							}
						}
						.quantity {
							font-size: 24rpx;
							color: #999999;
						}
					}
				}
				.goods-b {
					flex: 1;
					display: flex;
					&-l {
						flex: 1;
						.goods-date {
							font-size: 24rpx;
							color: #90949C;
						}
						.goods-seller {
							font-size: 24rpx;
							color: #90949C;
						}
					}
					&-r {
						display: flex;
						align-items: flex-end;
						.order-total {
							display: flex;						
						  	align-items: baseline;
							font-size: 24rpx;
							color: #999;
							.total-price {
								font-size: 34rpx;
								color: #333;
								font-weight: 600;
							}
						}
					}
				}
			}
		}

		/* 订单操作按钮样式 */
		.order-actions {
			display: flex;
			justify-content: flex-end;
			padding: 20rpx 24rpx 20rpx;

      .btns {
        display: flex;
        align-items: center;
      }

			.action-btn {
				height: 64rpx;
				line-height: 64rpx;
				padding: 0 30rpx;
				border-radius: 32rpx;
				font-size: 26rpx;
				margin-left: 16rpx;
				background: #FFFFFF;
				color: #666;
				border: 1rpx solid #DDDDDD;
				position: relative;
				overflow: hidden;
				transition: all 0.3s ease;

				&:after {
					content: '';
					position: absolute;
					top: 50%;
					left: 50%;
					width: 0;
					height: 0;
					background: rgba(255, 255, 255, 0.3);
					border-radius: 50%;
					transform: translate(-50%, -50%);
					transition: width 0.5s, height 0.5s;
				}

				&:active:after {
					width: 200%;
					height: 200%;
					opacity: 0;
				}

				&.pay {
					background: #FA452D;
					color: #FFFFFF;
					border: none;

					&:active {
						background: #ff5252;
						transform: translateY(2rpx);
					}
				}

				&.cancel {
					background: #FFFFFF;
					color: #666;
					border: 1rpx solid #DDDDDD;

					&:active {
						background: #f5f5f5;
						transform: translateY(2rpx);
					}
				}
			}
		}
	}

	/* 加载更多样式 */
	.uni-load-more {
		display: flex;
		flex-direction: row;
		height: 80rpx;
		align-items: center;
		justify-content: center;
	}

	.uni-load-more__text {
		font-size: 24rpx;
		color: #999999;
	}
</style>
